<?php
include(APP_PATH.'/sms/global.php');
class sms_util_system {
	/**
	 * 对外提供发送系统消息接口
	 * Enter description here ...
	 * @param unknown_type $reciever
	 * @param unknown_type $reciever_id
	 * @param unknown_type $content
	 * @param unknown_type $sender_name
	 * @param unknown_type $target
	 * @param unknown_type $time
	 * @param unknown_type $servername
	 * @param unknown_type $title
	 * @param unknown_type $senderid
	 */
	public static function send($reciever, $reciever_id, $content, $sender_name, $target, $time, $servername='', $title='',$senderid=0){
		if(preg_match('/(^[a-z0-9]+)(?:\|[a-z0-9]+)?/',$sender_name)){
			$sender_name = '[:'.$sender_name.':]';
		}
		$params = array(
			'reciever'=>$reciever,
			'reciever_id'=>$reciever_id,
			'title'=>$title,
			'content'=>$content,
			'sender_name'=>$sender_name,
			'target'=>serialize($target),
			'time'=>time(),
			'senderid' => $senderid?$senderid:0,
		);
		if(!$servername)
		{
			$servername = $_SERVER['SERVER_NAME'];
		}
		$params['checksum'] = call_user_func_array(array('sms_util_verifier', 'systemChecksum'), $params);
		$url = "http://".$servername."/~sms.system.send";
		$content = http_request($url, $params);
		$ret = json_decode($content);
		
		if(!$ret or !$ret->result){
			// retry again;
			$content = http_request($url, $params);
			$ret = json_decode($content);
		}
		return $ret and $ret->result;
	}
	
	public static function sendCiteNotice($uid=''){
		$uid = $uid?$uid:Controller::$login['uid'];
		$key = CACHE_KEY_NEW_CITE_PRE.$uid;
		include_once DOCUMENT_PATH.'/api/api_nga/sdk/API_Client.php';
		if(!($cache = MemRow::getCache($key)) || time()-$cache['time']>CACHE_EXPIRY_TIME || $cache['flag']==0){
			//如果没有cache，新建cache
			//没有发送或者已经过期
			$api = new API_Client();//调用动态接口，获取好友转给他的转贴。
			if($feed = $api->feed_get($uid, 10, 15)){
				$str = '<div class="sms_feed"><h3>您的好友转帖给您：</h3><ul>	';
				foreach ($feed AS $v){
					$row = unserialize($v['feed_data']);
					$str.='<li><a href="http://i.178.com/?uid='.$v['uid'].'" target="_blank">'.$v['username'].'</a> 转帖给您：<span class="brackets-l-icon"></span><a href="'.$row['url'].'" target="_blank" >'.$row['title'].'</a><span class="brackets-r-icon"></span></li>';
				}
				$str.='</ul></div>';
			}
			/**
			 * 发送短信代码
			 */
			self::send(NULL,$uid,$str,':nga:','1',time(),'i.178.com','今天您的好友给您的精彩转帖');
				//跟新memcache数据
			MemRow::setCache($key, array('uid'=>$uid,'flag'=>1,'time'=>time()),0);	
		}
		return ;
	}
	
	public static function upSmsStatus($senderid,$reciverid,$type){
		if(!($senderid && $reciverid && $type)) return false;
		$system = Model::factory('sms_model_system');
		$row = $system->getSysNoticeByUid($senderid,$reciverid,$type);
		$id = $row['sms_id'];
		$target = unserialize($row['target']);
		$sender_name = sms_util_text::parseSenderName($row['sender']);
		$regex = "`\[\:([a-z0-9]+)\|([a-z0-9]+)\:\]`";
		if(preg_match($regex, $type, $match)){
			$type = $match[2];
		}else
			$type =$target['type'];
		if(key_exists($type, $_SERVER['LOCALE']['apps'][$sender_name][1]['return'])){
			$target['return'] = eval_template($_SERVER['LOCALE']['apps'][$sender_name][1]['return'][$type], $target);
		}else{
			$target['return'] = eval_template($_SERVER['LOCALE']['apps'][$sender_name][1]['return'][$target['type']], $target);
		}
		$system->updateTarget($id, $target);
	}
	
	
	/**
	* 远程打开URL
	* @param string $url   打开的url，　
	* @param int $limit   取返回的数据的长度
	* @param string $post   要发送的 POST 数据，如uid=1&username=xxxx
	* @param string $cookie 要模拟的 COOKIE 数据，如uid=123&auth=a2323sd2323
	* @param bool $bysocket TRUE/FALSE 是否通过SOCKET打开
	* @param string $ip   IP地址
	* @param int $timeout   连接超时时间
	* @param bool $block   是否为阻塞模式
	* @return    取到的字符串
	*/
	function socket_request($url, $limit = 0, $post = '', $cookie = '', $bysocket = FALSE, $ip = '', $timeout = 15, $block = TRUE) {
	$return = '';
	$matches = parse_url($url);
	!isset($matches['host']) && $matches['host'] = '';
	!isset($matches['path']) && $matches['path'] = '';
	!isset($matches['query']) && $matches['query'] = '';
	!isset($matches['port']) && $matches['port'] = '';
	$host = $matches['host'];
	$path = $matches['path'] ? $matches['path'].($matches['query'] ? '?'.$matches['query'] : '') : '/';
	$port = !empty($matches['port']) ? $matches['port'] : 80;
	if($post) {
		$out = "POST $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		//$out .= "Referer: $boardurl\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "Content-Type: application/x-www-form-urlencoded\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host\r\n";
		$out .= 'Content-Length: '.strlen($post)."\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cache-Control: no-cache\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
		$out .= $post;
	} else {
		$out = "GET $path HTTP/1.0\r\n";
		$out .= "Accept: */*\r\n";
		//$out .= "Referer: $boardurl\r\n";
		$out .= "Accept-Language: zh-cn\r\n";
		$out .= "User-Agent: $_SERVER[HTTP_USER_AGENT]\r\n";
		$out .= "Host: $host\r\n";
		$out .= "Connection: Close\r\n";
		$out .= "Cookie: $cookie\r\n\r\n";
	}
	$fp = @fsockopen(($ip ? $ip : $host), $port, $errno, $errstr, $timeout);
	if(!$fp) {
		return '';//note $errstr : $errno \r\n
	} else {
		stream_set_blocking($fp, $block);
		stream_set_timeout($fp, $timeout);
		@fwrite($fp, $out);
		$status = stream_get_meta_data($fp);
		if($block){
			if(!$status['timed_out']) {
				while (!feof($fp)) {
					if(($header = @fgets($fp)) && ($header == "\r\n" || $header == "\n")) {
						break;
					}
				}

				$stop = false;
				while(!feof($fp) && !$stop) {
					$data = fread($fp, ($limit == 0 || $limit > 8192 ? 8192 : $limit));
					$return .= $data;
					if($limit) {
						$limit -= strlen($data);
						$stop = $limit <= 0;
					}
				}
			}
		}
		@fclose($fp);
		return $return;
	}
}

	public static function getTableName($uid)
	{
    	return 'app_sms_notice_'.intval($uid)%NOTICE_TABLE_NUM;
	}

	/**
	 * 生成MT激活码
	 * 
	 * 生成16位大小字母和数字的字符串
	 *
	 * @param int $prefix 激活码前缀
	 * @return str
	 */
	public static function genKey($prefix = 2)
	{
		mt_srand();
		$seed 	= base_convert(md5(print_r($_SERVER, 1).microtime()), 16, 35);
		$seed 	= $seed . 'zZ' . strtoupper($seed);
		$hash 	= '';
		$max  	= strlen($seed) - 1;
		$length = 15;
		for($i = 0; $i < $length; $i++) $hash .= $seed[mt_rand(0, $max)];
		return $prefix . $hash;
	}
	
	
	public static function getVerifyCode($para=array(),$key){
		if(empty($para)) return false;
		$code = '';
		foreach($para as $v){
			$code.=$v;
		}
		return md5($code.$key);
	}
	
	
	/**
	 * 发送邀请码
	 *
	 */
	public static function sendActiveCode(){
		$system = Model::factory('sms_model_system');
//		$arr_user = $system->getDuelUsers();
		$arr_user = array(
						0=>array('uid'=>4892787,'username'=>'bigbear1113'),
						1=>array('uid'=>5164303,'username'=>'fza'),
						2=>array('uid'=>1495375,'username'=>'泡er泡')
					);
		if($arr_user){
			foreach ($arr_user as $row){
				$key = self::genKey(2);
				$content = '<a href="http://mtdmx.178.com" target="_blank"><img src="/res/sms/images/mt.jpg" border="0" align="middle" /></a>
   感谢您一直以来对地精科技的支持。您由此获得了一次体验地精新科技的机会。
地精科技研究所特发此邀请函，并附上最新推出的《MT大冒险》游戏内测激活码一枚.
<span style="font-size:16px;color:#900;text-align:center"><b>'.$key.'</b></span>
激活地址：<a href="http://i.178.com/~app/id/2" target="_blank">http://i.178.com/~app/id/2 </a>
游戏官网：<a href="http://mtdmx.178.com" target="_blank">http://mtdmx.178.com </a>
官方论坛：<a href="http://bbs.178.com/forum-552-1.html" target="_blank" >http://bbs.178.com/forum-552-1.html</a>（提交内测bug、交流、活动专用）';
				$flag=0;
				if(self::send($row['username'],$row['uid'],$content,'[:nga:]','',time(),'')){
					$flag=1;
				}
				$system->setActiveCodeLog($row['uid'],$key,$flag);
				if($flag){
					echo '\n send invite code to user '.$row['username'].' success!!\n';
				}
				else echo  '\n send invite code to user '.$row['username'].' failed !!\n';
				sleep(1);
			}
		}
	}
}